﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Transactions;

using LINQtoSQLDataProvider;

namespace Dragon.Prototype1.Service
{
    public class CodeService
    {
        public bool GetNextCode(string codeName, int step, Func<int, string> calculateNextCode)
        {
            using (WMSDataContext db = new WMSDataContext())
            {
                //if the code name exists in the database
                if (db.Codes.Count(e => e.CodeName == codeName) == 0)
                {
                    throw new ArgumentOutOfRangeException(string.Format("<{0}> is not a valid code name in the database", codeName));
                }

                //get the last code
                Code code = db.Codes.Single(e => e.CodeName == codeName);
                code.CurrentNo+=step;
                code.LastCode = calculateNextCode.Invoke(code.CurrentNo);

                try
                {
                    db.SubmitChanges();
                }
                catch (ChangeConflictException)
                {
                    return false;
                }
            }
            return true;
        }
    }
}
